var app = angular.module('routerApp', ['ui.bootstrap', 'ui.router'], function($httpProvider) {
	$httpProvider.defaults.withCredentials = true;
});

//配置angular的路由
app.config(function($stateProvider, $urlRouterProvider) {
	$urlRouterProvider.otherwise("welcome");
	$stateProvider.state("welcome", {
		url: '/welcome',
		templateUrl: 'html/welcome.html',
		controller: 'welcomeCtrl'
	}).state("main", {
		url: '/main',
		templateUrl: 'html/main.html',
		controller: 'mainCtrl'
	}).state("main.index", {
		url: '/main/index',
		templateUrl: 'html/main/index.html',
		controller: 'main_indexCtrl'
	}).state("main.mySort", {
		url: '/main/mySort',
		templateUrl: 'html/main/mySort.html',
		controller: 'main_mySortCtrl'
	}).state("main.showNotes", {
		url: '/main/showNotes',
		templateUrl: 'html/main/showNotes.html',
		controller: 'main_showNotesCtrl'
	}).state("main.personalInfo", {
		url: '/main/personalInfo',
		templateUrl: 'html/main/personalInfo.html',
		controller: 'main_personalInfoCtrl'
	}).state("main.searchBySort", {
		url: '/main/searchBySort',
		templateUrl: 'html/main/searchBySort.html',
		controller: 'main_searchBySortCtrl'
	}).state("main.dataStatistics", {
		url: '/main/dataStatistics',
		templateUrl: 'html/main/dataStatistics.html',
		controller: 'main_dataStatisticsCtrl'
	}).state("main.scientificReview", {
		url: '/main/scientificReview',
		templateUrl: 'html/main/scientificReview.html',
		controller: 'main_scientificReviewCtrl'
	}).state("main.friends", {
		url: '/main/friends',
		templateUrl: 'html/main/friends.html',
		controller: 'main_friendsCtrl'
	}).state("main.takeNotes", {
		url: '/main/takeNotes',
		templateUrl: 'html/main/takeNotes.html',
		controller: 'main_takeNotesCtrl'
	});
});

app.controller("welcomeCtrl", function($scope, $http, $state) {

	//发送邮箱设置
	$scope.setting = {
		vcodeMaxime: 180,
	}
	$scope.message = "暂无信息";
	//用户
	$scope.user = {
		userId: "", //用户名
		userPWD: "", //密码
		vcode: "", //验证码
	}
	//语言包
	$scope.textFile;
	//获取语言包
	$scope.getLanguagePack = function(Local, PageName, Language) {
		var datas = {
			language: Language,
			local: Local,
			pageName: PageName
		}
		$http({
			url: "PasyyWEB/Welcome/getLanguagePack",
			method: 'GET',
			params: datas
		}).success(function(data) {
			$scope.textFile = data;
		}).error(function(response) {
			/*失败信息*/
		});
	}
	$scope.initLanguage = function() {
		$scope.getLanguagePack(true, "welcome", "null");
	}

	$scope.changeLanToChinese = function() {
		$scope.getLanguagePack(false, "welcome", "zh_CN");
	}
	$scope.changeLanToTraditionalChinese = function() {
		$scope.getLanguagePack(false, "welcome", "zh_HK");
	}
	$scope.changeLanToEnglish = function() {
		$scope.getLanguagePack(false, "welcome", "en_US");
	}
	$scope.changeLanToKorean = function() {
		$scope.getLanguagePack(false, "welcome", "ko_KR");
	}
	$scope.changeLanToJapanese = function() {
		$scope.getLanguagePack(false, "welcome", "ja_JP");
	}
	//登陆,注册,忘记密码
	//登陆
	$scope.login = function() {
		var data = {
			userEmail: $scope.user.userId,
			userPWD: $scope.user.userPWD,
			vcode: $scope.user.vcode,
		}
		$http({
			params: data,
			url: "PasyyWEB/Welcome/loginByEmail",
			method: 'post',
			withCredentials: true, //必须要填
		}).success(function(datas) {
			alert(datas.message);
			if(datas.state == false) {
				$scope.sendVCode();
			} else {
				$state.go("main.index")
			}

		}).error(function(response) {
			/*失败信息*/
		});
	}
	//注册
	$scope.register = function() {
		var data = {
			userEmail: $scope.user.userId,
			userPWD: $scope.user.userPWD,
			sixNum: $scope.user.vcode,
		}
		$http({
			url: "PasyyWEB/Welcome/registerByEmail",
			method: 'post',
			params: data
		}).success(function(datas) {
			alert(datas.message);

			//进入main页面
			$state.go("main.index")

		}).error(function(response) {
			/*失败信息*/
		});
	}
	//忘记密码
	$scope.resetPWD = function() {
		var data = {
			userEmail: $scope.user.userId,
			userPWD: $scope.user.userPWD,
			sixNum: $scope.user.vcode,
		}
		$http({
			url: "PasyyWEB/Welcome/resetPWDByEmail",
			method: 'post',
			params: data
		}).success(function(datas) {
			alert(datas.message);
			//进入main页面
			//			$state.go("main/index");
		}).error(function(response) {
			/*失败信息*/
		});
	}
	//发送普通登陆验证码图片
	$scope.sendVCode = function() {
		$("#vcode").attr("src", "PasyyWEB/Welcome/getVeriFicationCode?time=" + new Date().getTime())
	}
	//根据邮箱发送验证码
	$scope.sendVCodeToEmail = function(num) {
		var VcodeforRegister;
		if(num == 1) {
			VcodeforRegister = true;
		} else if(num == 0) {
			VcodeforRegister = false;
		}
		var data = {
			userEmail: $scope.user.userId,
			forRegister: VcodeforRegister,
		}
		$http({
			url: "PasyyWEB/Welcome/sendVerificationCodeToEmail",
			method: 'post',
			params: data
		}).success(function(datas) {
			alert(datas.message);
			if(datas.state == "true") {
				var leftTime = 5 * 60;
				var time = setInterval(function() {
					$scope.textFile.sendVerificationCode = leftTime-- + "s";
					if($scope.textFile.sendVerificationCode == '0s') {
						$scope.textFile.sendVerificationCode = "重新发送";
						$scope.setting.vcodeMaxime = 5 * 60;
						clearInterval(time);
					}
				}, 1000);
			} else {
				alert("验证码发送失败");
			}
		}).error(function(response) {
			/*失败信息*/
			alert("验证码已发送失败");
		});
	}

	//3个模态框
	$scope.openRegisterModal = function() {
		$('#loginModal').modal('hide');
		$('#registerModal').modal('show');
	}
	$scope.openLoginModal = function() {
		$('#registerModal').modal('hide');
		$('#loginModal').modal('show');
	}
	$scope.openForgetPWDModal = function() {
		$('#loginModal').modal('hide');
		$('#forgetPWDModal').modal('show');
	}

})
app.controller("mainCtrl", function($scope, $http, $state) {
	$state.go("main.personalInfo");
	//设置对应元素宽高
	$scope.setElement = function() {
		var height1 = window.screen.height;
		var height2 = $("header").height();
		$("article").height(height1 - height2);
	}
	$scope.user = {
		nickName: "",
		userState: "",
		signature: "",
		head: "",
		sex: true
	}
	//初始化用户信息
	$scope.initUserInfo = function() {
		$http({
			url: "PasyyWEB/Main/initUserInfo",
			method: 'get',
			withCredentials: true, //必须要填
		}).success(function(datas) {
			if(datas.state == 1) {
				$scope.user = datas.user;
				if(datas.user.head == "") {
					$(".head").attr("src", "img/1.png");
				}

			}
		}).error(function() {

		});
	}

	$scope.changeState = function() {
		if($scope.user.userState = "在线") {
			$(".stateCircle").css("background-color", "greenyellow");
		} else {
			$(".stateCircle").css("background-color", "red");
		}
	}

	//注销
	$scope.logout = function() {
		alert("注销成功!")
		$http({
			url: "PasyyWEB/Welcome/logOut",
			method: 'get',
			withCredentials: true, //必须要填
		}).success(function(datas) {
			alert(datas.message);
		}).error(function() {

		});
	}

	//1.个人笔记
	//笔记的类别
	$scope.ShowSortOfNotes = false;
	$scope.showMyNotes = false;
	$scope.showMyFriends = false;
	$scope.notes;
	$scope.LoadNotesDate = function() {
		$scope.notes = [{
				"2019": [{
					1: [{
						1: ["大便便", "小便便"]
					}, {
						11: ["大便便", "小便便"]
					}, {
						22: ["大便便", "小便便"]
					}]
				}, {
					2: [{
						1: ["大便便", "小便便"]
					}, {
						11: ["大便便", "小便便"]
					}, {
						22: ["大便便", "小便便"]
					}]
				}, {
					3: [{
						1: ["大便便", "小便便"]
					}, {
						11: ["大便便", "小便便"]
					}, {
						22: ["大便便", "小便便"]
					}]
				}, {
					4: [{
						1: ["大便便", "小便便"]
					}, {
						11: ["大便便", "小便便"]
					}, {
						22: ["大便便", "小便便"]
					}]
				}, {
					5: [{
						1: ["大便便", "小便便"]
					}, {
						11: ["大便便", "小便便"]
					}, {
						22: ["大便便", "小便便"]
					}]
				}]
			},
			{
				"2018": [{
					1: [{
						1: ["大便便", "小便便"]
					}, {
						11: ["大便便", "小便便"]
					}, {
						22: ["大便便", "小便便"]
					}]
				}, {
					2: [{
						1: ["大便便", "小便便"]
					}, {
						11: ["大便便", "小便便"]
					}, {
						22: ["大便便", "小便便"]
					}]
				}, {
					3: [{
						1: ["大便便", "小便便"]
					}, {
						11: ["大便便", "小便便"]
					}, {
						22: ["大便便", "小便便"]
					}]
				}, {
					4: [{
						1: ["大便便", "小便便"]
					}, {
						11: ["大便便", "小便便"]
					}, {
						22: ["大便便", "小便便"]
					}]
				}, {
					5: [{
						1: ["大便便", "小便便"]
					}, {
						11: ["大便便", "小便便"]
					}, {
						22: ["大便便", "小便便"]
					}]
				}]
			},
		]

		notes = $scope.notes;
		//清空子元素
		$(".thenotes").empty();
		//年的数量
		var $yearNum = notes.length;
		//notes集合的java解析   notes=List<map<String,list<map<int,list<map<int,list<String>>>>>>>  还是花了整整6小时写完此多重循环

		//循环添加年的li
		for(var i = 0; i < $yearNum; i++) {
			for(var key in $scope.notes[i]) {
				//获得月的数组(map集合<int,list>)
				var monthArray = $scope.notes[i][key];
				//获得月的数量
				var monthNum = monthArray.length;
				//通过计算获得本年所有篇数 脑袋剧痛苦(但为了节省后端开销,不打算使用sql查询而是通过已给出的数据在前端得到需要的值,加油,奥利干)
				$totalInYear = 0;
				for(var j1 = 0; j1 < monthNum; j1++) {
					for(var key1 in monthArray[j1]) {
						var dayArray = monthArray[j1][key1];
						for(var k = 0; k < dayArray.length; k++) {
							for(var key2 in dayArray[k]) {
								$everyArray = dayArray[k][key2];
								for(var l = 0; l < $everyArray.length; l++) {
									$totalInYear++;
								}
							}
						}
					}
				}
				//年的动态标签
				$yearLi = $('<li class="year " >' + key + '年' + '<span class="badge">' + $totalInYear + '</span>' + '</li>');
				//计算月
				for(var j = 0; j < monthNum; j++) {
					for(var key in monthArray[j]) {
						var dayArray = monthArray[j][key];
						$totalInMonth = 0;
						for(var k1 = 0; k1 < dayArray.length; k1++) {
							for(var key1 in dayArray[k1]) {
								$everyArray = dayArray[k1][key1];
								for(var l = 0; l < $everyArray.length; l++) {
									$totalInMonth++;
								}
							}
						}

						$monthUl = $('<ul class="month" >' + key + '月' + '<span class="badge">' + $totalInMonth + '</span>' + '</ul>');

						//获得天的数组(map<int,list>集合)

						//获得天的数量
						var dayNum = dayArray.length;

						for(var k = 0; k < dayArray.length; k++) {
							for(var key in dayArray[k]) {
								$totalInDay = 0;
								$everyArray = dayArray[k][key];
								for(var l1 = 0; l1 < $everyArray.length; l1++) {
									$totalInDay++;
								}

								$dayLi = $('<li class="day" >' + key + '号' + '<span class="badge">' + $totalInDay + '</span>' + '</li>');
								//获得当天所有日记的数组

								for(var l = 0; l < $everyArray.length; l++) {
									$noteTitle = $('<ul class="noteTitle" >' + $everyArray[l] + '</ul>');
									$dayLi.append($noteTitle);
								}

								//月的ul里添加天的li
								$monthUl.append($dayLi);
							}
						}
						//年的li里添加月的ul
						$yearLi.append($monthUl);

					}
				}
				//总的ul里添加年的li
				$(".thenotes").append($yearLi);
			}

		}
		$(".thenotes").children(".year").eq(0).addClass("btn btn-primary");
		$(".year").hide();
		$(".month").hide();
		$(".day").hide();
		$(".noteTitle").hide();

		$(".year").on("click", function(e) {
			$(this).addClass("btn btn-primary");
			$(this).siblings().removeClass("btn btn-primary");
			e.stopPropagation();
			$(this).children(".month").toggle();
			$(this).siblings().children(".month").hide();
		});
		$(".month").on("click", function(e) {
			e.stopPropagation();
			$(this).children(".day").toggle();
			$(this).siblings().children(".day").hide();
		});
		$(".day").on("click", function(e) {
			e.stopPropagation();
			$(this).children(".noteTitle").toggle();
			$(this).siblings().children(".noteTitle").hide();
		});
	}
	$scope.LoadNotesDate();
	$scope.madeLableByNotesDate = function() {
		//类别
		$scope.ShowSortOfNotes = !$scope.ShowSortOfNotes;
		//notes集合的java解析   notes=List<map<String,list<map<int,list<map<int,list<String>>>>>>>  还是花了整整3小时写完此多重循环
		$(".year").toggle();
	}

})
app.controller("main_dataStatisticsCtrl", function($scope, $http) {
	$("#dataStatisticsModal").modal("show");
})
app.controller("main_friendsCtrl", function($scope, $http) {

})
app.controller("main_indexCtrl", function($scope, $http) {

})
app.controller("main_mySortCtrl", function($scope, $http) {

})
app.controller("main_personalInfoCtrl", function($scope, $http) {
	$scope.theHeadFile = "";
	$scope.uploadPic = function() {
		$("#theHeadFile").click();

	}
	$("#theHeadFile").change(function() {
		run(this, function(data) {
			$scope.theHeadFile = data;
			$("#pseronalInfoModal .head").attr("src", data);
		});
	})
	$scope.initUserInfo2 = function() {
		$http({
			url: "PasyyWEB/Main/initUserInfo",
			method: 'get',
			withCredentials: true, //必须要填
		}).success(function(datas) {
			if(datas.state == 1) {
				$scope.user = datas.user;
				if(datas.user.head == "") {
					$(".head").attr("src", "img/1.png");
				}

			}
			if($scope.user.sex == true) {
				$('input:radio').eq(0).attr('checked', 'true');
			} else {
				$('input:radio').eq(1).attr('checked', 'true');
			}
		}).error(function() {

		});

	}

	//保存用户信息
	$scope.saveUserInfo = function() {
		var data = {
			userHead: $scope.theHeadFile,
			userNickName: $scope.user.nickName,
			userSex: $("input[type='radio']:checked").val(),
			userSignature: $scope.user.signature,
		}
		$http({
			params: data,
			url: "PasyyWEB/Main/saveUserInfo",
			method: 'post',
			withCredentials: true, //必须要填
		}).success(function(datas) {
			alert(datas.message);

		}).error(function(response) {
			/*失败信息*/
		});
	}
	//将图片转换成base格式
	function run(input_file, get_data) {
		/*input_file：文件按钮对象*/
		/*get_data: 转换成功后执行的方法*/
		if(typeof(FileReader) === 'undefined') {
			alert("抱歉，你的浏览器不支持 FileReader，不能将图片转换为Base64，请使用现代浏览器操作！");
		} else {
			try {
				/*图片转Base64 核心代码*/
				var file = input_file.files[0];
				//这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
				if(!/image\/\w+/.test(file.type)) {
					alert("请确保文件为图像类型");
					return false;
				}
				var reader = new FileReader();
				reader.onload = function() {
					get_data(this.result);
				}
				reader.readAsDataURL(file);
			} catch(e) {
				alert('图片转Base64出错啦！' + e.toString())
			}
		}
	}
})
app.controller("main_scientificReviewCtrl", function($scope, $http) {

})
app.controller("main_searchBySortCtrl", function($scope, $http) {

})
app.controller("main_showNotesCtrl", function($scope, $http) {

})
app.controller("main_takeNotesCtrl", function($scope, $http) {
	var E = window.wangEditor
	var editor = new E('#editor')
	editor.customConfig.uploadImgShowBase64 = true // 使用 base64 保存图片
	//创建一个
	$scope.makeARichText = function() {

		// 或者 var editor = new E( document.getElementById('editor') )
		editor.create();
	}
	$scope.makeARichText();

	$scope.getEditorHtml = function() {
		alert(editor.txt.html());
	}
})